require"lsqlite3"

local db = sqlite3.open("shows.db")

local function print_show_list()
	for name in db:urows"SELECT name from shows ORDER BY name ASC" do
		print (name)
	end
end

local function cleanup_filename(s)
	return s:gsub("%?", ""):gsub(":", "-"):gsub("/", " "):gsub("\\", "_"):gsub("%*", "_")
end

local function get_show_id(show_name)
	local show_id
	local stmt = db:prepare"SELECT id from shows where name = ?"
	stmt:bind_values(show_name)
	for id in stmt:urows() do
		assert(not show_id, "Two Id for the same show")
		show_id = id
	end
	return assert(show_id, "Show not found")
end

local function print_show_filenames(show_name, season)
	local show_id = get_show_id(show_name)
	local stmt
	if season then
		stmt = db:prepare[[
SELECT season_number, episode_number_in_season, title
FROM episodes
WHERE show_id = ? AND season_number = ?
ORDER BY episode_number
]]
		stmt:bind_values(show_id, season)
	else
		stmt = db:prepare[[
SELECT season_number, episode_number_in_season, title
FROM episodes
WHERE show_id = ?
ORDER BY episode_number
]]
		stmt:bind_values(show_id)
	end

	for s, e, t in stmt:urows() do
		local base = cleanup_filename(string.format("%s - %dx%2.2d - %s", show_name, s, e, t))

		print(base .. ".avi")
	end
end

if not arg[1] then
	print_show_list()
else
	print_show_filenames(arg[1], arg[2])
end

